import React, { Component } from 'react';
import { Input, Button, List } from 'antd';

import store from './store'



import {getInputChangeAction,getAddItemAction,getDeleteItemAction} from './store/actionCreators'

class Todolist extends Component {
  constructor(props) {
    super(props);

    this.state = store.getState()
    console.log(this.state)

    this.handerInputChange=this.handerInputChange.bind(this)
    this.handleStoreChange=this.handleStoreChange.bind(this)
    this.handleBtnClick=this.handleBtnClick.bind(this)

    store.subscribe(this.handleStoreChange)

  }

  // 封装action
  handleItemDelete(index){
    // const action={
    //   type:DELETE_TODO_ITEM,
    //   index
    // }
    const action=getDeleteItemAction(index)
    store.dispatch(action)
  }


  handleBtnClick(){
    // const action ={
    //   type:ADD_TODO_ITEM,
    // }
    const action=getAddItemAction()
    store.dispatch(action)
  }


  handleStoreChange(){
    console.log('handleStoreChange')
    this.setState(store.getState())
  }
  handerInputChange(e){
    // const action={
    //   type:CHANGE_INPUT_VALUE,
    //   value:e.target.value
    // }

    //方法2
    const action=getInputChangeAction(e.target.value)
    store.dispatch(action)
  }

  render () {
    return (
      <div style={{ marginTop: "10px", marginLeft: '10px' }}>
        <div>
          <Input
            value={ this.state.inputValue }
            placeholder="Basic usage"
            style={{ width: '300px', marginRight: '20px' }}
            onChange={this.handerInputChange}/>
          <Button type="primary" onClick={this.handleBtnClick}>提交</Button>
          <List
            style={{ marginTop: '10px', width: '300px' }}
            bordered
            dataSource={this.state.list}
            renderItem={(item,index) => <List.Item onClick={this.handleItemDelete.bind(this,index)}>{item}</List.Item>}
          />
        </div>
      </div>
    );
  }
}

export default Todolist;